#include "Gsys.h"


/*
---------------------------

---------------------------
*/
CEntity::CEntity() 
{
	m_pPrev = NULL;
	m_pNext = NULL;
	m_pManager = NULL;
};

CEntity::~CEntity() 
{

}

INT CEntity::Enter() 
{
	if(m_pManager != NULL)
	{
		m_pManager->Insert(this);
		return TRUE;
	}

	return FALSE;
}

INT CEntity::Execute()
{
	return FALSE;
}

INT CEntity::Out()  
{
	if(m_pManager != NULL)
	{
		m_pManager->Remove(this);
		return TRUE;
	}

	return FALSE;
}

void CEntity::Del()  
{
}

void CEntity::SetManager(CEntityManager* pManager)
{
	m_pManager = pManager;
}

INT CEntity::SetPrev(CEntity* pEntity)
{
	m_pPrev = pEntity;
	return TRUE;
}

INT CEntity::SetNext(CEntity* pEntity)
{
	m_pNext = pEntity;
	return TRUE;
}

CEntity* CEntity::GetPrev()
{
	return m_pPrev;
}

CEntity* CEntity::GetNext()
{
	return m_pNext;
}


/*
---------------------------

---------------------------
*/
CEntityManager::CEntityManager()
{
	m_Head.SetNext(&m_Tail);
	m_Head.SetPrev(&m_Tail);
	m_Tail.SetNext(&m_Head);
	m_Tail.SetPrev(&m_Head);
}

CEntityManager::~CEntityManager()
{
	
}


void CEntityManager::Insert(CEntity* pEntity)
{
	if(!Find(pEntity))
	{
		pEntity->SetNext(&m_Tail);
		pEntity->SetPrev(m_Tail.GetPrev());
		m_Tail.GetPrev()->SetNext(pEntity);
		m_Tail.SetPrev(pEntity);
		m_iEntityNum++;
	}
}

void CEntityManager::Remove(CEntity* pEntity)
{
	if(Find(pEntity))
	{
		pEntity->GetPrev()->SetNext(pEntity->GetNext());
		pEntity->GetNext()->SetPrev(pEntity->GetPrev());
		m_iEntityNum--;
	}
}

void CEntityManager::RemoveAll()
{
#if 1
	CEntity *pNode;
	CEntity *pTmp;

	pNode = m_Head.GetNext();
	while (pNode != &m_Tail) 
	{
		pTmp = pNode->GetNext();
		pNode->GetPrev()->SetNext(pNode->GetNext());
		pNode->GetNext()->SetPrev(pNode->GetPrev());
		pNode->SetPrev(NULL);
		pNode->SetNext(NULL);
		pNode = pTmp;
	}
#endif
	m_Head.SetNext(&m_Head);
	m_Head.SetPrev(&m_Head);
	m_iEntityNum = 0;
}

void CEntityManager::Update()
{
	//int iCnt = 0;
	CEntity *pNode = m_Head.GetNext();
	CEntity *pNext;
	while(pNode != &m_Tail)
	{
		//printf(" entity update :%d \n", iCnt);
		pNext = pNode->GetNext();
		pNode->Execute();
		pNode = pNext;

		//printf(" entity update :%d \n", iCnt++);
	}
}

void CEntityManager::DelAll()
{
	CEntity *pNode = m_Head.GetNext();
	CEntity *pNext;
	while(pNode != &m_Tail)
	{
		pNext = pNode->GetNext();
		pNode->Del();
		pNode = pNext;
	}
}

void CEntityManager::Exit()
{
	DelAll();
	RemoveAll();
}

BOOL CEntityManager::Find(CEntity* pEntity)
{
	CEntity *pNode = m_Head.GetNext();
	while(pNode != &m_Tail)
	{
		if(pNode == pEntity)
		{
			return TRUE ;
		}
		else
		{
			pNode = pNode->GetNext();
		}
	}

	return FALSE ;
}

